package cn.ly.design.structure;

/**
 * 享元模式的主要目的是实现对象的共享，即共享池，
 * 当系统中对象多的时候可以减少内存的开销，通常与工厂模式一起使用。
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

public class Flyweight {
	
	public static void main(String[] args) {
		Connection conn = ConnectionPool.getPool().getConnection();
		System.out.println(conn);
	}

}

class ConnectionPool{
	private Vector<Connection> pool;  
	
	//公有属性
    private String url = "jdbc:mysql://localhost:3306/test";  
    private String username = "root";  
    private String password = "root";  
    private String driverClassName = "com.mysql.jdbc.Driver";  
    
    private int poolSize = 100;
    private static ConnectionPool instance = new ConnectionPool();
    private Connection conn;
    
    public static ConnectionPool getPool(){
    	return instance;
    }
    
    private ConnectionPool(){
    	pool = new Vector<Connection>(poolSize);
    	
    	for(int i=0; i<poolSize; i++){
    		try{
    			Class.forName(driverClassName);
    			conn = DriverManager.getConnection(url,username,password);
    			pool.add(conn);
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    }
    
    //获得连接
    public Connection getConnection() {
    	Connection c = null;
    	if(poolSize > 0){
    		c = pool.get(0);
    		pool.remove(c);
    		return c;
    	}else{
    		try{
    			c = DriverManager.getConnection(url,username,password);
    		}catch(Exception e){}
    	}
    	return c;
    }
}


